<?php

namespace App\Models\Invoice;

use App\Traits\UuidTrait;
use Illuminate\Database\Eloquent\Model;

class Title extends Model
{
    use UuidTrait;

    const TABLE = 'invoice_titles';
    protected $table = self::TABLE;

    protected $casts = [
        'value' => 'array',
        'is_default' => 'boolean'
    ];

    public $attributes = [
        'value' => '[]'
    ];

    const TYPE_PERSONAL = 0;
    const TYPE_COMPANY = 1;

    public $timestamps = false;


    public static function getDefaultTitle(string $appUserID = null): array
    {
        $title = null;

        if ($appUserID) {
            if (!$title = self::where('app_user_id', $appUserID)->where('is_default', true)->first()) {
                $title = self::where('app_user_id', $appUserID)->first();
            }
        }

        if (!$value = optional($title)->value ?: []) {
            $value = ['title' => '个人', 'type' => self::TYPE_PERSONAL];
        } else {
            $value['type'] = $title->type;
        }

        return $value;
    }
}
